<template>
  <div class="app-container">
    <!-- 采购计划维护 -->
    <div class="search-bar">
      <!-- 搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="采购单号" prop="code">
          <el-input
            v-noSpace
            v-model="queryParams.code"
            placeholder="请输入采购单号"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="companyCode">
          <el-select-v2
            v-model="queryParams.companyCode"
            filterable
            :options="allCompanyCode"
            value-key="value"
            :props="codeProps"
            placeholder="请输入供应商编号"
            class="!w-[192px]"
            clearable
            @change="handleQuery()"
          />
        </el-form-item>

        <!-- <el-form-item label="原材料" prop="companyCode">
          <el-input v-noSpace
            v-model="queryParams.companyCode"
            placeholder="请输入原材料"
            clearable
            
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="采购日期" prop="productCode">
          <el-select
            v-model="queryParams.productCode"
            placeholder="请选择产品名称"
            style="width: 250px"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in productList"
              :key="item.codeValue"
              :label="item.codeName"
              :value="item.codeValue"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            class="!w-[192px]"
            clearable
            filterable
            @change="handleQuery"
          >
            <el-option
              v-for="item in filteredStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购日期" prop="timeScopes">
          <el-date-picker
            v-model="queryParams.timeScopes"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button
            type="warning"
            v-hasPerm="'sys:purchase:edit'"
            icon="edit"
            @click="handleEdit('add')"
          >
            新增
          </el-button>
          <!-- <el-button type="warning" icon="menu" @click="handleEdit({}, 'add')">新增</el-button> -->
        </el-form-item>
      </el-form>

      <!-- 生产单列表 -->
    </div>

    <!-- 表格 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" show-overflow-tooltip @row-click="handClikRow">
        <el-table-column prop="code" width="200" label="采购订单编号" align="center" />
        <el-table-column prop="companyName" label="供应商" align="center" width="200">
          <template #default="scope">
            {{ ` ${scope.row.companyName} - ${scope.row.companyCode}` }}
          </template>
        </el-table-column>

        <el-table-column prop="issueDate" label="采购日期" width="140px" align="center" />
        <el-table-column prop="refCode" label="归属合同" width="140px" align="center" />
        <el-table-column prop="deliveryDate" label="送货日期" width="140px" align="center" />

        <el-table-column prop="salesMan" label="业务员" width="140px" align="center">
          <template #default="scope">
            {{
              salesPersonList.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="orderAmount" label="总金额" width="140px" align="center">
          <template #default="scope">
            {{ scope.row.orderAmount.toFixed(2) || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="120">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.approvalRemark || '暂无备注'"
              placement="top-start"
            >
              <el-tag v-if="scope.row.status === 1" type="warning">待审核</el-tag>

              <el-tag v-if="scope.row.status === 2" type="success">已审核采购单</el-tag>

              <el-tag v-if="scope.row.status === 3" type="danger">审核拒绝</el-tag>

              <el-tag v-if="scope.row.status === 4" type="warning">部分收货</el-tag>
              <el-tag v-if="scope.row.status === 5" type="success">已收货</el-tag>
              <el-tag v-if="scope.row.status === 6" type="danger">已拒收</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" align="center" width="200" />
        <el-table-column prop="createTime" label="创建时间" align="center" width="200" />
        <el-table-column prop="remark" label="备注" align="center" width="200" />
        <!-- <el-table-column prop="qty" label="状态" align="center" /> -->
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="handleEdit('view', scope.row)">
              查看
            </el-button>

            <el-button
              v-hasPerm="'sys:purchase:app'"
              v-if="scope.row.status === 1"
              type="warning"
              link
              size="small"
              @click="handleApprovedDialog(scope.row)"
            >
              审核
            </el-button>
            <el-button
              v-hasPerm="'sys:purchase:edit'"
              v-if="scope.row.status === 3"
              type="warning"
              link
              size="small"
              @click="handleReAudit(scope.row)"
            >
              再次提交审核
            </el-button>
            <el-button
              v-hasPerm="'sys:purchase:edit'"
              type="warning"
              link
              size="small"
              v-if="scope.row.status == 1 || scope.row.status == 3"
              @click="handleEdit('edit', scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="'sys:purchase:car'"
              type="danger"
              v-if="scope.row.status == 2 || scope.row.status == 4"
              link
              size="small"
              @click="handleAssignParking(scope.row)"
            >
              分配车位
            </el-button>
            <el-button
              v-hasPerm="'sys:purchase:del'"
              type="danger"
              v-if="scope.row.status == 1 || scope.row.status == 3"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="mt-2">
      <el-table v-loading="loading" :data="rowTableData">
        <el-table-column label="物料名称" align="center" prop="productName" />

        <el-table-column label="数量" align="center">
          <template #default="scope">
            {{ scope.row.qty || 0 }} {{ unitFormat(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column label="单价(元)" align="center" prop="unitPrice" />
        <el-table-column label="金额(元)" align="center" prop="amount">
          <template #default="scope">
            {{ scope.row.amount.toFixed(2) || 0 }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="qty" label="状态" align="center" /> -->
      </el-table>
    </el-card>

    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormDataRef"
        :model="dialogFormData"
        label-width="120px"
        :disabled="formDisabled"
        :rules="rules"
      >
        <el-row>
          <el-col v-if="dialogFormData.parentCode || !formDisabled" :span="12">
            <el-form-item label="采购类型" prop="category">
              <el-select
                v-model="dialogFormData.category"
                placeholder="请选择采购类型"
                clearable
                filterable
                class="w-full"
                @visible-change="getCategory"
              >
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col v-if="dialogFormData.category == '1'" :span="12">
            <el-form-item label="生产单号" prop="batch">
              <el-select
                v-model="dialogFormData.parentCode"
                placeholder="请选择生产单号"
                clearable
                filterable
                class="w-full"
                @visible-change="getbatch"
              >
                <el-option
                  v-for="item in batchOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="供应商" prop="companyCode">
              <el-select-v2
                v-model="dialogFormData.companyCode"
                filterable
                clearable
                :options="allCompanyCode"
                value-key="value"
                :props="codeProps"
                placeholder="请输入供应商编号"
                class="w-full"
                @visible-change="getContactList(dialogFormData.companyCode || '')"
                @change="clearContact"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="采购日期" prop="issueDate">
              <el-date-picker
                v-model="dialogFormData.issueDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="送货日期" prop="deliveryDate">
              <el-date-picker
                v-model="dialogFormData.deliveryDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="otherRef">
              <el-select-v2
                v-model="dialogFormData.otherRef"
                filterable
                clearable
                :options="contactList"
                value-key="value"
                :props="codeProps"
                placeholder="请输入联系人"
                class="w-full"
                @visible-change="getContactPhone"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="">
              <el-input v-noSpace v-model="contactPhone" disabled class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属合同" prop="refCode">
              <el-input v-noSpace v-model="dialogFormData.refCode" disabled class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员" prop="salesMan">
              <el-select
                v-model="dialogFormData.salesMan"
                filterable
                clearable
                placeholder="请输入业务员"
                style="width: 240px"
              >
                <el-option
                  v-for="item in salesPersonList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value.toString()"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="dialogFormData.remark"
                type="textarea"
                maxlength="500"
                show-word-limit
                placeholder="请输入备注"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider />
      <p>采购明细</p>

      <el-form
        ref="dialogFormDataProRef"
        :model="dialogFormDataPro"
        label-width="120px"
        :disabled="formDisabled"
        :rules="rulesPro"
      >
        <el-row v-if="!formDisabled">
          <el-col :span="12">
            <el-form-item label="物料名称" prop="productName">
              <el-select
                v-model="dialogFormDataPro.productName"
                placeholder="请选择物料名称"
                clearable
                filterable
                no-data-text="当前供应商未签订合同，请先签订合同！"
                @change="changeproductName"
                @visible-change="getContractList"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-noSpace v-model="dialogFormDataPro.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item :label="`数量（${unitValue?.label || ''}）`" prop="qty">
              <el-input-number v-model="dialogFormDataPro.qty" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                v-model="dialogFormDataPro.unitPrice"
                :step="0.01"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input-number v-model="calculatedAmount" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12" />
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="addProDuct">添加产品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table v-loading="loading" :data="rowTableData">
        <el-table-column label="物料名称" align="center" prop="productName" />
        <!-- <el-table-column label="单位" align="center" prop="unit" /> -->
        <el-table-column label="数量" align="center" prop="qty">
          <template v-if="!formDisabled" #default="scope">
            <div class="flex-center">
              <el-input
                v-noSpace
                v-model="scope.row.qty"
                class="!w-24"
                size="small"
                @input="updateAmount(scope.row)"
              >
                <template #suffix>
                  {{ unitFormat(scope.row.unit) }}
                </template>
              </el-input>
            </div>
          </template>
          <template v-else #default="scope">
            <div class="flex-center">
              {{ scope.row.qty }}
              {{ unitFormat(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="unitPrice" align="center">
          <template v-if="!formDisabled" #default="scope">
            <el-input-number
              :step="0.01"
              :min="0"
              v-model="scope.row.unitPrice"
              size="small"
              class="!w-24"
              @input="updateAmount(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="amount">
          <template #default="scope">
            {{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column v-if="!formDisabled" label="操作" align="center">
          <template #default="scope">
            <el-button size="small" link type="danger" @click="deleteRow(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template v-if="!formDisabled" #footer>
        <div v-if="dialog.type != 'view'" class="dialog-footer flex-center">
          <el-button v-debounce="submit" type="primary">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog
      v-model="dialogApp.visible"
      :title="dialogApp.title"
      width="500px"
      @close="handleCloseDialogApp"
    >
      <el-input v-noSpace v-model="approvedRemake" type="textarea" placeholder="请输入审核意见" />

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handlePass('pass')">通 过</el-button>
          <el-button type="primary" @click="handlePass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配车位 -->
    <el-dialog v-model="detailDialogVisible.visible" title="分配车位" width="800px">
      <el-scrollbar max-height="600px">
        <el-form ref="formRef" :model="formData" :rules="formRules" class="p-2" label-width="100px">
          <div class="grid grid-cols-2 gap-2">
            <el-form-item label="订单号" prop="code">
              <el-input
                v-noSpace
                v-model="formData.code"
                placeholder="请选择订单号"
                class="w-full"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="司机" prop="deliveryUser">
              <el-input
                v-noSpace
                v-model="formData.deliveryUser"
                placeholder="请填写司机"
                class="w-full"
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-noSpace v-model="formData.licensePlate" placeholder="请填写车牌号" />
            </el-form-item>

            <el-form-item label="联系电话" prop="driverPhone">
              <el-input v-noSpace v-model="formData.driverPhone" placeholder="请填写联系电话" />
            </el-form-item>

            <el-form-item label="卸车车位" prop="loadingPosition">
              <el-select
                v-model="formData.loadingPosition"
                placeholder="请选择卸车车位"
                class="w-full"
              >
                <el-option
                  v-for="item in positionList"
                  :key="item.parkingLocation"
                  :label="item.parkingLocation"
                  :value="item.parkingLocation"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="flex justify-center">
          <el-button>取消</el-button>
          <el-button type="primary" @click="handleAssignParkingSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import configApi, { ConfigType } from "@/api/config/config";
import PurchasApi, { PurchasPageVO, PurchasPageQuery } from "@/api/order/purchas";

import inventoryApi from "@/api/warehouseManage/inventory";
import { FormItemRule } from "element-plus/es";
import suppInfoApi from "@/api/suppManage/suppInfo";

import UserAPI from "@/api/system/user";
import productPrice from "@/api/priceMaintenance/productPrice";
import { DeliveryOrderList } from "@/api/LogisticsManagement/deliveryOrderMaintenance";
import parkingSpaceInquiryApi, {
  parkingSpaceInquiryResult,
} from "@/api/LogisticsManagement/parkingSpaceInquiry";

const contactPhone = ref("");

const batchOptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getbatch = () => {
  inventoryApi
    .getbatchApi({ pageNum: 1, pageSize: 999, statusList: [1, 3, 4, 5, 6] })
    .then((data) => {
      batchOptions.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.code,
      }));
    })
    .finally(() => {});
};

// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
  type: "",
});
const categoryOptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型

function getCategory() {
  configApi.getConfigListByType(ConfigType.PURCHASE_CATEGORY).then((res) => {
    categoryOptions.value = (res || []).map((item: any) => ({
      value: item.codeValue,
      label: item.codeName,
    }));
  });
}
// const allCompanyCode = ref<{ code: string; count: number }[]>([]);

// 审核弹窗
const dialogApp = reactive({
  id: NaN,
  title: "",
  visible: false,
});

//所有供应商编号-下拉框
const codeProps = {
  label: "label",
  value: "value",
};

// 审核意见
const approvedRemake = ref("");

// 定义 rowTableData 的类型
interface RowTableDataItem {
  productName?: string;
  unit?: string;
  qty?: number;
  unitPrice?: number;
  amount?: number;
  productCode?: string;
}

const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};
const rowTableData = ref<RowTableDataItem[]>([]);

const dialogFormDataRef = ref(ElForm);

const dialogFormDataProRef = ref(ElForm);

//row信息
const rowObj = ref<any | null>(null);

const formDisabled = ref(false);

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const allCompanyCode = ref<{ value: string; label: string; contractCode: string }[]>([]);

interface DialogFormData {
  code?: string;
  companyCode?: string;
  parentCode?: string;
  companyName?: string;
  issueDate?: string;
  purchaseOrderDetailList?: RowTableDataItem[];
  category?: string;
  deliveryDate?: string;
  otherRef?: string;
  refCode?: string;
  salesMan?: string;
  remark?: string;
}

interface DialogFormDataPro {
  productName?: string;
  unit?: string;
  qty?: number;
  unitPrice?: number;
  amount?: number;
  productCode?: string;
}

const rules = reactive<Record<string, FormItemRule[]>>({
  parentCode: [{ required: true, message: "关联生产单是必填项", trigger: "blur" }],
  companyCode: [{ required: true, message: "供应商是必填项", trigger: "blur" }],
  issueDate: [{ required: true, message: "采购日期是必填项", trigger: "change" }],
  deliveryDate: [{ required: true, message: "送货日期是必填项", trigger: "change" }],
});

const rulesPro = reactive<Record<string, FormItemRule[]>>({
  productName: [{ required: true, message: "材料名称是必填项", trigger: ["blur"] }],
  companyName: [{ required: true, message: "供应商是必填项", trigger: ["blur", "change"] }],
  deliveryDate: [{ required: true, message: "采购日期是必填项", trigger: ["blur", "change"] }],
  qty: [
    { required: true, message: "数量是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "数量必须是一个数字", trigger: ["blur", "change"] },
    { min: 0, type: "number", message: "数量必须大于等于0", trigger: ["blur", "change"] },
  ],
  unitPrice: [
    { required: true, message: "单价是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "单价必须是一个数字", trigger: ["blur", "change"] },
    { min: 0, type: "number", message: "单价必须大于等于0", trigger: ["blur", "change"] },
  ],
});

const calculatedAmount = computed(() => {
  return Number(((dialogFormDataPro.qty || 0) * (dialogFormDataPro.unitPrice || 0)).toFixed(2));
});
// 新增/修改form
const dialogFormData = reactive<DialogFormData>({});
const dialogFormDataPro = reactive<DialogFormDataPro>({});

const loading = ref(false);

const queryParams = reactive<PurchasPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<PurchasPageVO[]>();

const total = ref(0);

const queryFormRef = ref(ElForm);

// 查询
function handleQuery() {
  loading.value = true;
  console.log("queryParams", queryParams);
  queryParams.statusList = queryParams.status ? [Number(queryParams.status)] : [1, 2, 3, 4, 5, 6];

  PurchasApi.getPage(queryParams)
    .then((data: any) => {
      pageData.value = [...(data.list as any)];
      console.log("data", data);
      total.value = data.total;
      rowTableData.value = [];
    })
    .catch((err) => {
      console.log(err);

      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}

const getContactPhone = () => {
  console.log("contactPhone", contactList.value);

  contactPhone.value = contactList.value.find((item) => item.value == dialogFormData.otherRef)?.tel;
};

function deleteRow(index: any) {
  rowTableData.value?.splice(index, 1);
}

function updateAmount(row: any) {
  row.amount = (parseFloat(row.qty) || 0) * (parseFloat(row.unitPrice) || 0);
}

function handClikRow(row: any) {
  getEditDetail(row);
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  //todo

  handleQuery();
}

const filteredStatusList = ref([
  { value: 1, label: "待审核" },
  { value: 2, label: "已审核待采购" },
  { value: 3, label: "审核拒绝" },
  { value: 4, label: "部分收货" },
  { value: 5, label: "已收货" },
  { value: 6, label: "已拒收" },
]);

const getContractList = () => {
  if (!dialogFormData?.companyCode) return (options.value = []);
  PurchasApi.getTypePage({
    pageNum: 1,
    pageSize: 999,
    productType: "2",
    companyCode: dialogFormData?.companyCode,
  })
    .then((data) => {
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
        unit: item.unit,
      }));
    })
    .finally(() => {});
};

function addProDuct() {
  dialogFormDataProRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    // 判断productName是否重复如果重复就不添加
    const isDuplicate = rowTableData.value.some(
      (item) => item.productName === dialogFormDataPro.productName
    );
    if (isDuplicate) {
      ElMessage.error("材料名称重复，请重新选择");
      return;
    }
    rowTableData.value.push({
      productName: dialogFormDataPro.productName,
      unit: unitValue.value.value,
      qty: dialogFormDataPro.qty,
      unitPrice: dialogFormDataPro.unitPrice,
      amount: calculatedAmount.value,
      productCode: dialogFormDataPro.productCode,
    });
    clearDialogFormDataPro();
  });
}

function clearDialogFormDataPro() {
  let data = {
    productName: "",
    unit: "",
    qty: 0,
    unitPrice: 0,
    amount: 0,
    productCode: "",
  };
  Object.assign(dialogFormDataPro, { ...data });
}
function clearDialogFormData() {
  let data = {
    companyCode: "",
    parentCode: "",
    companyName: "",
    issueDate: "",
    purchaseOrderDetailList: [],
    category: "",
    code: "",
    remark: "",
    deliveryDate: "",
    otherRef: "",
    refCode: "",
    salesMan: "",
  };
  Object.assign(dialogFormData, { ...data });
  contactPhone.value = "";
}
async function handleEdit(type: string, row?: any) {
  if (type == "add") {
    dialog.title = "新增";
    formDisabled.value = false;
    rowTableData.value = [];
  } else if (type == "edit") {
    dialog.title = "修改";
    console.log("修改", row);

    Object.assign(dialogFormData, row);
    getContactList(row.companyCode);

    if (row.parentCode) {
      getCategory();

      dialogFormData.category = "1";
    }
    getEditDetail(row);
    formDisabled.value = false;
  } else {
    dialog.title = "查看";
    Object.assign(dialogFormData, row);
    getContactList(row.companyCode);

    if (row.parentCode) {
      getCategory();

      dialogFormData.category = "1";
    }
    formDisabled.value = true;
  }
  dialog.type = type;
  dialog.visible = true;
}

function handleCloseDialog() {
  dialog.visible = false;
  rowTableData.value = [];
  contactList.value = [];

  dialogFormDataRef.value.resetFields();
  dialogFormDataRef.value.clearValidate();
  clearDialogFormDataPro();
  clearDialogFormData();
}
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 产品列表
const productList = ref<
  {
    label: string;
    value: string;
    unit: string;
  }[]
>([]);
function changeproductName(val: any) {
  console.log(val);
  //先清空表单
  dialogFormDataPro.productName = "";
  dialogFormDataPro.unitPrice = 0;
  dialogFormDataPro.qty = 0;

  dialogFormDataPro.productCode = val.value;
  dialogFormDataPro.productName = val.label;
  unitValue.value = unitOptions.value.find((item) => item.value === val.unit) as any;
  //获取最新价格
  productPrice
    .getProductPriceList({ productCode: val.value, pageNUm: 1, pageSize: 1 })
    .then((data) => {
      dialogFormDataPro.unitPrice = data[data.length - 1].amount;
    });
}

const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};

function submit() {
  console.log(dialogFormData);
  dialogFormDataRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    if (!rowTableData.value.length) {
      ElMessage.error(`请添加采购明细`);
      return;
    }
    dialogFormData.purchaseOrderDetailList = rowTableData.value;
    PurchasApi.addformData(dialogFormData)
      .then((data: any) => {
        ElMessage.success(`操作成功`);
        handleQuery();
        dialog.visible = false;
        clearDialogFormDataPro();
        clearDialogFormData();
      })
      .catch((err) => {
        // handleCloseDialog();
        // handleResetQuery();
      })
      .finally(() => {});
  });
}

function getEditDetail(row: any) {
  PurchasApi.detailList(row?.code)
    .then((data: any) => {
      rowTableData.value = data || [];
      // ElMessage.success(`操作成功`);
      // handleQuery();
    })
    .catch((err) => {
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {});
}

//打开审核窗口
function handleApprovedDialog(row: any) {
  dialogApp.id = row.id;
  dialogApp.visible = true;
}
//关闭审核窗口
function handleCloseDialogApp() {
  dialogApp.visible = false;
  dialogApp.id = NaN;
  approvedRemake.value = "";
}

//是否通过
function handlePass(type: string) {
  const status = type === "pass" ? 2 : 3;
  PurchasApi.check({
    id: dialogApp.id,
    status: status,
    approvalRemark: approvedRemake.value,
  })
    .then((data) => {
      ElMessage.success(`操作成功`);
      handleQuery();
      dialogApp.visible = false;
      approvedRemake.value = "";
    })
    .catch((error) => {})
    .finally(() => {
      loading.value = false;
    });
}

//重新审核
function handleReAudit(row: any) {
  PurchasApi.addformData({
    id: row.id,
    status: 1,
  })
    .then((data) => {
      ElMessage.success(`操作成功`);
      handleQuery();
    })
    .catch((error) => {})
    .finally(() => {
      loading.value = false;
    });
}
//分配车位
const detailDialogVisible = reactive({ visible: false });
const formData = ref<{
  code: string;
  deliveryUser: string;
  licensePlate: string;
  driverPhone: string;
  loadingPosition: string;
  id: number;
}>({
  id: NaN,
  code: "",
  deliveryUser: "",
  licensePlate: "",
  driverPhone: "",
  loadingPosition: "",
});
const formRules = reactive<Record<string, FormItemRule[]>>({
  code: [{ required: true, message: "订单号不能为空", trigger: "blur" }],
  deliveryUser: [{ required: true, message: "请选择司机", trigger: "blur" }],

  loadingPosition: [{ required: true, message: "请选择装车车位", trigger: "blur" }],
  driverPhone: [{ required: true, message: "司机手机号不能为空", trigger: "blur" }],
  licensePlate: [
    { required: true, message: "车牌号不能为空", trigger: "blur" },
    {
      pattern:
        /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
      message: "请输入正确的车牌号",
      trigger: "blur",
    },
  ],
});
const handleAssignParking = (row: any) => {
  detailDialogVisible.visible = true;
  formData.value = { ...row };
};

const positionList = ref<parkingSpaceInquiryResult[]>([]);
//获取所有卸车位
const getPositionList = () => {
  parkingSpaceInquiryApi.pageQuery({ pageNum: 1, pageSize: 999, spotType: 1 }).then((res) => {
    console.log(res, "res");
    positionList.value = res.list;
  });
};
const formRef = ref();
//提交分配车位
const handleAssignParkingSubmit = () => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      console.log(formData.value, "formData.value");
      parkingSpaceInquiryApi
        .saveOrUpdate({
          parkingLocation: formData.value.loadingPosition,
          licensePlate: formData.value.licensePlate,
          sourceCode: formData.value.code,
          spotType: 1,
        })
        .then(() => {
          ElMessage.success("操作成功");
          handleQuery(); // 刷新列表
          detailDialogVisible.visible = false; // 关闭对话框
        })
        .then(() => {
          PurchasApi.addformData({
            id: formData.value.id,
            licensePlate: formData.value.licensePlate,
          }).then((data: any) => {
            formRef.value.resetFields();
            formData.value = {
              id: NaN,
              code: "",
              deliveryUser: "",
              licensePlate: "",
              driverPhone: "",
              loadingPosition: "",
            };
            // ElMessage.success(`操作成功`);
            handleQuery();
          });
        });
    } else {
      ElMessage.error("请填写完整信息");
    }
  });
};

//删除
function handleDelete(id: number) {
  ElMessageBox.confirm("是否确认删除该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      PurchasApi.deleteById(id)
        .then((data: any) => {
          ElMessage.success(`操作成功`);
          handleQuery();
        })
        .catch((err) => {})
        .finally(() => {});
    })
    .catch(() => {});
}
const salesPersonList = ref<any[]>([]);
const salesProps = {
  label: "employeeName",
  value: "employeeId",
};
//联系人列表
const contactList = ref<any[]>([]);

//查询所有供应商和业务员信息
function handleAllCompanyQuery() {
  suppInfoApi.getContractList({ pageNum: 1, pageSize: 99, status: "1" }).then((data: any) => {
    allCompanyCode.value = data.list.map((item: any, idx: number) => ({
      value: item.companyCode,
      label: `${item.companyCode} - ${item.companyName}`,
      contractCode: item.code,
    }));
  });

  // 业务员列表
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    salesPersonList.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
    console.log(data, "data");
  });
}
function getContactList(code: string) {
  console.log(code, "code");

  if (!code) return;
  //根据供应商code获取合同
  console.log(
    allCompanyCode.value.filter((item: any) => item.value == code),
    "allCompanyCode"
  );

  dialogFormData.refCode = allCompanyCode.value.filter(
    (item: any) => item.value == code
  )[0].contractCode;

  suppInfoApi
    .getContactPage({ pageNum: 1, pageSize: 99, parentCode: code })
    .then((res) => {
      console.log(res, "根据客户查询联系人");
      //将联系人列表赋值给contactList.value
      contactList.value = res.map((item: any) => {
        return {
          id: item.id,
          tel: item.tel,

          label: item.contactPerson,
          value: item.id.toString(),
        };
      });
    })
    .then(() => {
      getContactPhone();
    });
}
//清空
const clearContact = () => {
  contactPhone.value = "";

  dialogFormData.otherRef = "";
  dialogFormData.refCode = "";
};
onMounted(() => {
  handleQuery();
  handleAllCompanyQuery();
  getUnitList();
  getPositionList();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
